<template>
  <div class="app-wrapper">
    <!-- 侧边栏 -->
    <div class="sidebar-container" :class="{ 'is-collapse': isCollapse }">
      <div class="logo-container">
        <img src="@/assets/logo.svg" alt="logo" class="logo" />
        <h1 v-show="!isCollapse" class="logo-title">管理系统</h1>
      </div>

      <el-scrollbar wrap-class="scrollbar-wrapper">
        <el-menu
          :default-active="activeMenu"
          :collapse="isCollapse"
          :unique-opened="true"
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
          router
        >
          <sidebar-item
            v-for="route in permissionRoutes"
            :key="route.path"
            :item="route"
            :base-path="route.path"
            :is-collapse="isCollapse"
          />
        </el-menu>
      </el-scrollbar>
    </div>

    <!-- 主区域 -->
    <div class="main-container">
      <!-- 头部导航 -->
      <div class="navbar">
        <div class="navbar-left">
          <div class="hamburger" @click="toggleSidebar">
            <el-icon>
              <Fold v-if="!isCollapse" />
              <Expand v-else />
            </el-icon>
          </div>

          <breadcrumb />
        </div>

        <div class="navbar-right">
          <span v-if="userStore.isTest" class="test-account-label"
            >测试账号</span
          >
          <span v-if="userStore.isTenant" class="tenant-label"
            >租户: {{ userStore.tenantId }}</span
          >

          <el-dropdown trigger="click">
            <div class="avatar-container">
              <el-avatar :size="32" :src="userStore.avatar" />
              <span class="username">{{ userStore.name }}</span>
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="goToProfile">
                  <el-icon><User /></el-icon>
                  个人中心
                </el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 主内容区 -->
      <div class="app-main">
        <router-view v-slot="{ Component }">
          <transition name="fade-transform" mode="out-in">
            <keep-alive :include="cachedViews">
              <component :is="Component" />
            </keep-alive>
          </transition>
        </router-view>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useUserStore } from "@/store/user";
import SidebarItem from "@/components/SidebarItem.vue";
import Breadcrumb from "@/components/Breadcrumb.vue";
import {
  ArrowDown,
  User,
  SwitchButton,
  Fold,
  Expand,
} from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import { constantRoutes, asyncRoutes } from "@/router";

const userStore = useUserStore();
const router = useRouter();
const route = useRoute();

const isCollapse = ref(false);
const cachedViews = ref([]); // 如有需要缓存的视图可以在这里设置

// 从路由获取菜单
const routes = computed(() => {
  return router.options.routes.filter((route) => {
    // 过滤掉隐藏菜单
    return !route.meta?.hidden;
  });
});

// 根据权限过滤路由
const permissionRoutes = computed(() => {
  // 显示常规路由
  const baseRoutes = constantRoutes.filter((route) => !route.meta?.hidden);

  // 如果是测试账号
  if (userStore.isTest) {
    // 测试账号可以看所有菜单，但不能修改数据
    return [
      ...baseRoutes,
      ...asyncRoutes.filter((route) => !route.meta?.hidden),
    ];
  }

  // 如果是管理员
  if (userStore.isAdmin) {
    // 管理员可以看所有菜单
    return [
      ...baseRoutes,
      ...asyncRoutes.filter((route) => !route.meta?.hidden),
    ];
  }

  // 其他角色根据权限显示菜单
  const filterRoutes = (routes) => {
    return routes.filter((route) => {
      if (route.meta && route.meta.permission) {
        const hasPermission = userStore.hasPermission(route.meta.permission);
        if (!hasPermission) return false;
      }

      if (route.children) {
        route.children = filterRoutes(route.children);
        if (route.children.length === 0 && !route.component) {
          return false;
        }
      }

      return !route.meta?.hidden;
    });
  };

  return [
    ...baseRoutes,
    ...filterRoutes(JSON.parse(JSON.stringify(asyncRoutes))),
  ];
});

// 当前激活菜单
const activeMenu = computed(() => {
  const { meta, path } = route;
  if (meta.activeMenu) {
    return meta.activeMenu;
  }
  return path;
});

// 切换侧边栏
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value;
};

// 前往个人资料页
const goToProfile = () => {
  router.push("/admin/profile");
};

// 处理登出
const handleLogout = () => {
  ElMessageBox.confirm("确定注销并退出系统吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await userStore.logoutAction();
        router.push("/login");
      } catch (error) {
        console.error("退出失败", error);
      }
    })
    .catch(() => {});
};

// 获取用户信息
onMounted(async () => {
  if (userStore.token && !userStore.name) {
    try {
      await userStore.getInfoAction();
    } catch (error) {
      console.error("获取用户信息失败", error);
    }
  }
});
</script>

<style scoped>
.app-wrapper {
  position: relative;
  height: 100vh;
  width: 100%;
  display: flex;
  overflow: hidden;
}

.sidebar-container {
  width: 220px;
  height: 100%;
  background: #202940;
  transition: width 0.28s;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.sidebar-container.is-collapse {
  width: 64px;
}

.logo-container {
  height: 60px;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #1e2538;
}

.logo {
  width: 32px;
  height: 32px;
}

.logo-title {
  color: #fff;
  font-size: 16px;
  margin-left: 10px;
  font-weight: 600;
  white-space: nowrap;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  width: calc(100% - 220px);
  transition: width 0.28s;
}

.is-collapse + .main-container {
  width: calc(100% - 64px);
}

.navbar {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  background: #fff;
}

.navbar-left {
  display: flex;
  align-items: center;
}

.hamburger {
  padding: 0 15px;
  cursor: pointer;
  font-size: 20px;
  color: #606266;
}

.navbar-right {
  display: flex;
  align-items: center;
}

.avatar-container {
  cursor: pointer;
  display: flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 24px;
  transition: all 0.3s;
}

.avatar-container:hover {
  background: #f5f7fa;
}

.username {
  margin: 0 8px;
  color: #606266;
  font-weight: 500;
}

.app-main {
  flex: 1;
  overflow-y: auto;
  background: #f7f8fc;
  height: calc(100vh - 60px);
  width: 100%;
  box-sizing: border-box;
}

.test-account-label {
  padding: 2px 8px;
  border-radius: 10px;
  background-color: #e6a23c;
  color: white;
  font-size: 12px;
  margin-right: 10px;
}

.tenant-label {
  padding: 2px 8px;
  border-radius: 10px;
  background-color: #409eff;
  color: white;
  font-size: 12px;
  margin-right: 10px;
}

/* 路由切换动画 */
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.5s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
</style>
